// index.js
// 获取应用实例
const app = getApp()

// 引入qqmapsdk 
const QQMapWX = require('../../lib/qqmap-wx-jssdk')
let qqmapsdk = new QQMapWX({key : 'WH2BZ-VCAC6-54QSL-E3Q5J-H2SZK-XJBCZ'})

Page({
  data: {
    hotId: '1',
    movies: [],
    offset: 0,
    city: '未选择'
  },

  // 加载当前定位
  getLocation(){
    qqmapsdk.reverseGeocoder({
      success:(res)=>{
        let city=res.result.address_component.city
        this.setData({
          city:city
        })
        // 在APP全局存储city名
        getApp().globalData.city=city
      },
      fail:(err)=>{
        console.warn(err)
      }
    })
  },

  // 是否用户授权
  isGetSetting() {
    return new Promise((resolve, rejected) => {
      wx.getSetting({
        success(res) {
          resolve(res.authSetting['scope.userLocation'])
        }
      })
    })
  },

   // 进入城市列表选择
  async cityList(){
    // 只有位置权限打开才可以进入
    let isLocationAuth = await this.isGetSetting();
    if(isLocationAuth){
      wx.navigateTo({
        url: '/pages/cityList/cityList',
      })
    }else{
      wx.showToast({
        title: '获取位置权限失败',
        icon:'error'
      })
    }
  },

  // 切换顶部选项卡
  // 需要考虑缓存
  hotNav(e) {
    let hotId = e.target.dataset.id
    this.setData({
      hotId: hotId,
      offset: 0,
      movies: []
    })
    let movies = wx.getStorageSync('hotId')
    if (movies) {
      this.setData({
        movies: JSON.parse(movies)
      })
    } else {
      this.loadData(this.data.hotId, this.data.offset)
        .then(res => {
          this.setData({
            movies: res
          })

          wx.setStorage({
            key: hotId,
            data: this.data.movies
          })
        })
    }

  },
  // 封装请求数据函数
  loadData(cid, offset) {
    // 弹出等待框
    wx.showLoading({
      title: '加载中,请稍后',
      mask: "true"
    })
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://api.tedu.cn/index.php?cid=${cid}&offset=${offset}`,
        method: "get",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success: res => {
          resolve(res.data)
          wx.hideLoading()
        }
      })
    })
  },
  entryDetail(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/movies/movies?id=' + id,
    })
  },
  // 获取用户位置授权
  getagree(){
    wx.authorize({
      scope: 'scope.userLocation',
      success:res=>{
        this.getLocation()
        getApp().globalData.locsuccess=true
      },
      fail:err=>{
        // 用户拒绝位置权限
        getApp().globalData.city=''
      }
    })
  },

  onLoad() {
    this.loadData(this.data.hotId, this.data.offset)
      .then(res => {
        this.setData({
          movies: this.data.movies.concat(res)
        })
        wx.setStorage({
          key: this.data.hotId,
          data: this.data.movies
        })
      })
      this.getagree()
     
  },

  // 获取从城市列表返回后获得的城市名字
  getfromcity(){
    let city=getApp().globalData.city
    city&&this.setData({
      city:city
    })
  },

  onShow:function(){
    this.getfromcity()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadData(this.data.hotId, this.data.offset).then(res => {
      // 停止下拉刷新
      wx.stopPullDownRefresh()
    })
  },


  /**
   * 页面上拉触底事件的处理函数
   */

  onReachBottom: function () {
    let offset = this.data.offset += 20
    this.loadData(this.data.hotId, offset)
      .then(res => {
        this.setData({
          movies: this.data.movies.concat(res)
        })
      })
  },

  getUserProfile(e) {

  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})